package com.wnx.job.modules.nms.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wnx.job.common.api.Const;
import com.wnx.job.common.api.PageResult;
import com.wnx.job.common.api.QueryPageBean;
import com.wnx.job.common.api.ResultData;
import com.wnx.job.common.mapstruct.ArticleMapper;
import com.wnx.job.common.service.RedisService;
import com.wnx.job.common.utils.StrUtils;
import com.wnx.job.modules.nms.dto.ArticleParam;
import com.wnx.job.modules.nms.model.NmsArticle;
import com.wnx.job.modules.nms.model.NmsChannel;
import com.wnx.job.modules.nms.service.NmsArticleService;
import com.wnx.job.modules.nms.service.NmsChannelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wangnaixing
 * @since 2021-12-16
 */
@Slf4j
@RestController
@RequestMapping("/nms/nmsArticle")
@Api(tags = "ArticleController",description = "咨询管理")
public class NmsArticleController {

    @Resource
    private NmsArticleService articleService;
    @Resource
    private RedisService redisService;
    @Resource
    private NmsChannelService channelService;

    /**
     * 新增咨讯信息
     * @param articleParam
     * @return
     */
    @PostMapping("/save")
    @ApiOperation("新增咨讯信息")
    public ResultData<String> save(@RequestBody @Validated ArticleParam articleParam){
        log.info("【=======系统正在增加咨讯中============】");
        articleService.saveArticle(articleParam);
        log.info("【==========系统新增咨讯成功！=============】");
        return ResultData.success(Const.ADD_ARTICLE_SUCCESS);
    }

    /**
     * 删除资讯信息
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    @ApiOperation("删除资讯信息")
    public ResultData<String> delete(@PathVariable(name = "id")Long id){
        log.info("【=========系统正在删除咨讯分类=======】");
        articleService.deleteArticle(id);
        log.info("【============系统删除咨讯分类成功！！===========】");
        return ResultData.success(Const.DELETE_ARTICLE_SUCCESS);
    }

    /**
     * 修改资讯
     * @param articleParam
     * @return
     */
    @PostMapping("/update")
    @ApiOperation("修改咨讯信息")
    public ResultData<NmsArticle> update(@RequestBody @Validated ArticleParam articleParam){
        log.info("【=======系统正在修改咨讯信息中，该公司的信息为：============】");
        NmsArticle nmsArticle = ArticleMapper.INSTANCE.toPojo(articleParam);
        nmsArticle.setUpdated(new Date());
        articleService.updateById(nmsArticle);
        log.info("【============系统修改咨讯信息成功！！===========】");
        return ResultData.success(Const.UPDATE_ARTICLE_SUCCESS,nmsArticle);
    }

    /**
     * 根据ID查询咨询信息
     * @param id
     * @return
     */
    @GetMapping("/findById/{id}")
    @ApiOperation("根据ID查询咨询信息")
    public ResultData<NmsArticle> findById(@PathVariable(name = "id")Long id){
        log.info("【=======系统正在根据ID查讯咨讯中....============】");
        NmsArticle article  =  articleService.getById(id);
        log.info("【=======系统正在根据ID查讯咨讯分类成功============】");
        return ResultData.success(Const.QUERY_ARTICLE_SUCCESS,article);
    }


    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @PostMapping("/findByPage")
    @ApiOperation("分页查询咨询信息")
    public ResultData<PageResult<NmsArticle>> findByPage(@RequestBody QueryPageBean queryPageBean){
        log.info("【==========系统正在分页查讯咨讯信息，前端分页查讯数据为{}：=============】",queryPageBean);
        PageResult<NmsArticle> pageResult = articleService.findByPage(queryPageBean);
        log.info("【==========系统正在分页查讯咨讯信息成功！=============】");
        return ResultData.success(pageResult);
    }


    /**
     * 根据咨询栏目ID获取对应咨询列表
     * @param id
     * @return
     */
    @GetMapping("/findListByChannelId/{id}")
    @ApiOperation("(网站前台)根据咨询栏目ID获取对应咨询列表")
    public ResultData<Map<String, Object>> findByChannelId(@PathVariable("id") Long id){
        HashMap<String, Object> resultMap = new HashMap<>(2);
        log.info("===========（网站前台）系统正在根据栏目ID获取文章列表===========================");
        //获取数据
        Page<NmsArticle> page = articleService.page(new Page<>(1, 7),
                new QueryWrapper<NmsArticle>().lambda().eq(NmsArticle::getChannelId,id));
        NmsChannel channel = channelService.getById(id);

        //标题字符你串长度截取
        List<NmsArticle> records = page.getRecords();
        records.forEach(x-> x.setTitle(StrUtils.CutString(x.getTitle())));

        resultMap.put("channel",channel);
        resultMap.put("articleList",records);
        return ResultData.success(Const.QUERY_ARTICLE_SUCCESS,resultMap);
    }

    /**
     * 根据咨询ID获取咨询详情
     * @param id
     * @return
     */
    @GetMapping("/getArticleDetail/{id}")
    @ApiOperation("(网站前台)根据咨询ID获取咨询详情")
    public ResultData<ArticleParam> getArticleDetail(@PathVariable(name = "id")Long id){
        log.info("==============（网站前台）根据咨询ID获取咨询详情！==============");;
        //获取前端文章ID

        //调用服务层，根据ID查询文章
        NmsArticle tbArticle= articleService.getById(id);
        ArticleParam article =  ArticleMapper.INSTANCE.toDto(tbArticle);

        //使用缓存观看数
        String redisKeyByViews = Const.ARTICLE_VIEW;
        //自增加1 ，返回之前的有序集合元素
        Double redisValueViews = redisService.zIncrementScore(redisKeyByViews, id, 1);

        if( redisValueViews != null){
            article.setViews(redisValueViews.intValue());
        }else {
            //存入缓存
            article.setViews(0);
            redisService.set(redisKeyByViews,0);
        }


        log.info("==============（网站前台）根据咨询ID获取咨询详情成功==============");;
        return ResultData.success(Const.QUERY_ARTICLE_SUCCESS,article);

    }


    /**
     * 获取当前热度文章
     */
    @GetMapping("/findHostArticleList")
    @ApiOperation("(网站前台)获取当前热度文章")
    public ResultData<List<NmsArticle>> findHostArticleList(){
        log.info("=========（网站前台）系统正在获取当前热度文章============");


        //获取文章观看记录前十的ID集合
        Set setRank = redisService.getZSetRank(Const.ARTICLE_VIEW, 1);
        int hostArticleCount = 0;

        //创建热点文章容器
        List<NmsArticle> articleList = new ArrayList<NmsArticle>();


        for (Object obj : setRank) {
            if( hostArticleCount <= 10) {
                //获取文章ID
                Long id = Long.parseLong(obj + "");

                //调用服务层，根据文章ID获取文章详情
                NmsArticle article = articleService.getById(id);

                articleList.add(article);
            }else {
                break;
            }
            hostArticleCount ++;
        }

        log.info("=========（网站前台）系统成功获取到当前热度文章！！！！============");
        return ResultData.success(Const.QUERY_ARTICLE_SUCCESS,articleList);



    }

}

